package com.draw.core;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "Line")
public class Line implements Serializable, Comparable<Line> {
	private static final long serialVersionUID = 7805631817167873614L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "id")
	private int id;

	@ManyToOne
	@JoinColumn(name = "drawing")
	private Drawing drawing;

	@ManyToOne
	@JoinColumn(name = "color", nullable = false)
	private Color color;

	@Column(name = "thickness", nullable = false)
	private int thickness;

	@OneToMany(mappedBy = "line")
	private Set<Vector> vectors;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public Drawing getDrawing() {
		return drawing;
	}

	public Color getColor() {
		return color;
	}

	public int getThickness() {
		return thickness;
	}

	public void setDrawing(Drawing drawing) {
		this.drawing = drawing;
	}

	public void setColor(Color color) {
		this.color = color;
	}

	public void setThickness(int thickness) {
		this.thickness = thickness;
	}

	public void addVector(Vector vector) {
		if (this.vectors == null) {
			this.vectors = new HashSet<Vector>();
		}
		this.vectors.add(vector);
		vector.setLine(this);
	}

	public Set<Vector> getVectors() {
		return this.vectors;
	}

	public void setVectors(Set<Vector> vectors) {
		if (vectors == null) {
			this.vectors = vectors;
		} else {
			this.vectors = new TreeSet<Vector>(vectors);
		}
	}

	public void unpopulate() {
		for (Vector v : vectors) {
			v.setLine(null);
		}
	}

	public void populate() {
		for (Vector v : vectors) {
			v.setLine(this);
		}
	}

	@Override
	public int compareTo(Line line) {
		if (this.vectors == null && line.vectors == null) {
			return 0;
		}
		if (this.vectors.size() == line.vectors.size()
				&& line.vectors.size() == 0) {
			return 0;
		}
		if (this.vectors == null || this.vectors.size() == 0) {
			return -1;
		}
		if (line.vectors == null || line.vectors.size() == 0) {
			return 1;
		}
		ArrayList<Vector> tv = new ArrayList<Vector>(new TreeSet<Vector>(this.vectors));
		ArrayList<Vector> lv = new ArrayList<Vector>(new TreeSet<Vector>(line.vectors));
		if (tv.get(0).compareTo(lv.get(lv.size()-1)) >= 0 ) {
			return 1;
		}
		if (lv.get(0).compareTo(tv.get(tv.size()-1)) >= 0 ) {
			return -1;
		}
		return 0;
	}
}
